<?php

namespace App\Http\Controllers;

use App\Models\Department;
use App\Models\System\SysLog;
use Illuminate\Support\Facades\Auth;
use App\Repositories\DepartmentRepository;
use App\Http\Requests\Logic\Department\QueryResource;
use App\Http\Requests\Logic\Department\StoreResource;
use App\Http\Requests\Logic\Department\UpdateResource;
use App\Http\Requests\Logic\Department\QueryCollection;
use App\Http\Requests\Logic\Department\DestroyResource;

class DepartmentController extends Controller
{
	protected $departmentRepository;

	/**
	 * DepartmentController constructor.
	 * @param DepartmentRepository $departmentRepository
	 */
	public function __construct(DepartmentRepository $departmentRepository)
	{
		$this->departmentRepository = $departmentRepository;
	}

	/**
	 * 获取部门信息集合
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @param QueryCollection $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(QueryCollection $request)
	{
		$user = Auth::user();
		$name = $request->get('name');
		$paginate = $request->get('paginate', 15);
		$query = $this->departmentRepository->getByCompany($user->company_id, $name);
		return success($query->paginate($paginate));
	}

	/**
	 * 获取部门详情
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @param QueryResource $request
	 * @param Department $department
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function show(QueryResource $request, Department $department)
	{
		return success($department);
	}

	/**
	 * 创建部门信息
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @param StoreResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \App\Exceptions\GeneralException
	 */
	public function store(StoreResource $request)
	{
		$attributes = $request->only(['company_id', 'name']);
		$department = $this->departmentRepository->store($attributes);
        SysLog::log(Auth::user(),'部门模块','创建部门');
		return stored($department);
	}

	/**
	 * 更新部门信息
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @param UpdateResource $request
	 * @param Department $department
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function update(UpdateResource $request, Department $department)
	{
		$name = $request->get('name');
		$department->update(['name' => $name]);
        SysLog::log(Auth::user(),'部门模块','更新部门信息');
        return updated($department);
	}

	/**
	 * Date: 18/04/2018
	 * @author George
	 * @param DestroyResource $request
	 * @param Department $department
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
	public function destroy(DestroyResource $request, Department $department)
	{
		$department->delete();
        SysLog::log(Auth::user(),'部门模块','删除部门');
        return deleted();
	}
}
